from pymongo import Connection
from time import time
import random
import csv
import subprocess
from XW_Inverter import XW_Inverter


PORT = '/dev/tty.usbserial-FTUTUPP2' #Enter the number needed here. 
ADDRESS = [0x89,0x65,0xc3]

Inverter = XW_Inverter(PORT,ADDRESS[0])

connection = Connection()
db = connection.string0001

## Building Load values! 

subprocess.call(['/Users/batterylab/seeya_node/ftpDraw'],shell=True)
blah = open('mb-250.log')
blah = blah.read()
blah = blah.split(',')
print blah

load = float(blah[6]) + float(blah[13])
load1 = float(blah[6])
load2 = float(blah[13])


#remove this from all UTC times to shift to Eastern Time - Timezone conversion. Valario addition, ask him for edits
timeZone=4*60*60

#Database collection formation

realtime = db.realtime
sensors = db.sensors
control = db.control.find_one({"label":0})
settings = db.settings
Nisensors = db.NIsensors.find_one({"label" : 0})


## Take database values!

invert_threshold = control["invert_threshold"]
charge_threshold = control["charge_threshold"]
status = control["status"]

chargeState = control["charge_state"]
sellState = control["sell_state"]

maxChargeRate = control["max_charge_current"]
maxSellRate = control["max_sell_current"]/3



meter = load
diff = 0
current = ((load-invert_threshold) * (1/40) )





Asoc= 0.0
Aiac= 0.0
Avac= 0.0
Aidc= 0.0
tpiac = 0.0
tpoac = 0.0

writer = ({"label":0})

#Initializations
iac = [0,0,0]
piac = [0,0,0]
poac = [0,0,0]
vac = [0,0,0]
vdc = [0,0,0]
idc = [0,0,0]
soc = [0,0,0]
TotCharAH = 0
TotSellAH = 0
PrevTime = 0

#function to retrieve data

for i in range(0,3):
	ii = str(i)
	
	Inverter.address = ADDRESS[i]
	
	iac[i] = Inverter.getACOutCurr()
	piac[i] = Inverter.getACInPowe1()
	poac[i] = Inverter.getACOutPower()
	vac[i] = Inverter.getACInVolt1()
	vdc[i] = Inverter.getDCInVolt()
	idc[i] = Inverter.getDCInCurr() 
	soc[i] = Inverter.getBatSOC()
	charge = Inverter.getChargeState()
	invert = Inverter.getInvertState()
	temperture = Inverter.getBatTemp()
	tpoac = poac[i] + tpoac
	tpiac = piac[i] + tpiac
	Niv0 = Nisensors['Niv0']
	Niv1 = Nisensors['Niv1']
	Niv2 = Nisensors['Niv2']
	Niv3 = Nisensors['Niv3']
	TNiv = Nisensors['tSum']
	SysTot = vdc[i] - TNiv/1000.0
	Asoc=soc[i]+ Asoc 
	Aiac=iac[i]+ Aiac
	Avac=vac[i]+ Avac
	Aidc=idc[i]+ Aidc
	## Writes the values to the database



#   if ((charge == 1) and (invert != 1)):
#   	deltaTime = (1000*(time()-timeZone) - PrevTime)/3600
#
#   	TotCharAH = TotCharAH + deltaTime * Aidc
#   	print TotCharAH
#   	print "Printing out TotCharAH"
#   
#   elif ((charge != 0) and (invert == 1)):
#   	deltaTime = (1000*(time()-timeZone) - PrevTime)/3600
#
#   	TotSellAH = TotSellAH + deltaTime * Aiac
#   	print TotSellAH
#   	print "Printing out TotSellAH"



for i in range(0,3):
	ii = str(i)
	writer.update( { 
		"idc" + ii : idc[i] ,
		"iac" + ii : iac[i] ,
		"piac" + ii : piac[i],
		"poac" + ii : poac[i], 
		"vac" + ii : vac[i] ,
		"vdc" + ii : vdc[i] ,
		"address" + ii : ADDRESS[i],
		"soc" + ii : soc[i],
		"charge" + ii : charge,
		"invert" + ii : invert,
		"temperature"+ ii : temperture,
		"time" : 1000*(time()-timeZone),
		"tpiac"  : tpiac,
		"tpoac"  : tpoac,
		"Aiac"   : Aiac,
		"Aidc"   : Aidc,
		"Niv0"	 : Niv0/1000.0,
		"Niv1"	 : Niv1/1000.0,
		"Niv2"	 : Niv2/1000.0,
		"Niv3"	 : Niv3/1000.0,
		"TNiv"	 : TNiv/1000.0,
		"SysTot" : SysTot,
		"TotSellAH": TotSellAH,
		"TotCharAH": TotCharAH
	} )
	
	## average values
	
sensors.update({'label':0},writer,True)






# running methods

## Nickle Zinc safety measures!!!
if( (Niv0 <= 1550) or (Niv1 <= 1550) or (Niv2 <= 1550) or (Niv3 <= 1550) ):
	#If below 1.55 volts, set the system to charge!!! 
	print "Sorry, system needs to charge!"
	Inverter.setSellMode(0)
	Inverter.setChargeState(1)
	Inverter.setMaxChargeRate(maxChargeRate)
	
elif( (Niv0 >= 1910) or (Niv1 >= 1910) or (Niv2 >= 1910) or (Niv3 >= 1910) ):
	#If above 1.91 volts, set the system to discharge!!!
	print "Sorry, system needs to sell"
	Inverter.setChargeState(0)
	Inverter.setSellMode(1)
	Inverter.setMaxSellAmp(maxSellRate)

else:
	#If the Nickle Zinc are fine, then you can safely go on with the system!

	if(status == 1):
		## Status equal to 1 means that we are in Autopilot mode!
		## make into function "runAuto"
		writer=({'label':0})
	
		if (load > invert_threshold):
		
			#values that are changed when the load is greater than the allowed threshold!|
			charge = False
			sell = True
			diff = (load - invert_threshold)
			meter = invert_threshold
		
			for i in range(0,3):
				ii=str(i)
			
				#Change Inverter Settings
				try:
					Inverter.address = ADDRESS[i]
					Inverter.setUserCommand()
					Inverter.setChargeState(0)
					Inverter.setSellMode(1)
					Inverter.setMaxSellAmp()
				except:
					print "There was an error writing to the Inverters, continuing with the code though: AUTO SELL WRITE"
			
				#Write the settings to the database!

				writer.update( { "idc" + ii : current/3.0 ,
					"status" + ii : 1 , 
					"address" + ii : ADDRESS[i],
					"charge" + ii : 0,
					"sell" + ii : 1,
					"time" : 1000*(time()-timeZone),
					"sellrate" : maxSellRate*200,
					"chargerate" : maxChargeRate
					} )
	
	else:
		## Status equal to 0 means that we are in Manual Mode!
	
		if (sellState == 1 and chargeState == 0):
		
			#values that are changed when the load is greater than the allowed threshold!|
			charge = False
			sell = True
			diff = (load - invert_threshold)
			meter = invert_threshold
		
			## If the sell state is set to True, do this!!!
			print "GOING INTO SELL!!!" 
		
			for i in range(0,3):
				ii = str(i)
				print ii
				##Change the Inverter Settings
			
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setChargeState(0)
				Inverter.setSellMode(1)
				Inverter.setMaxSellAmp(maxSellRate)
				print "Going into Sell!"
				"There was an error writing to the Inverters during MANUAL SELL WRITE"
				
		elif (sellState == 0 and chargeState == 1):
		
			#values that are changed when the load is greater than the allowed threshold!|
			charge = True
			sell = False
			diff = (load + charge_threshold)
			meter = diff
		
			print "GOING INTO CHARGE!!!!"
		
			for i in range(0,3):
				ii = str(i)
				print ii
				##Change the Inverter Settings
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setSellMode(0)
				try:
					Inverter.setForceCharge(1)
					Inverter.setMaxChargeRate(maxChargeRate)
				
					print "We have set it to charge"
				except ValueError:
					Inverter.setChargeState(1)
					Inverter.setMaxChargeRate(maxChargeRate)
					print "We have set it to charge (nF)"
				"There was an error writing to the Inverters during MANUAL CHARGE WRITE"
		elif (sellState == 0 and chargeState == 0):
		
			print "SHUT IT DDDOOOWWWNNNN"
		
			for i in range(0,3):
				ii = str(i)
				print ii
				##Change the Inverter Settings
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setSellMode(0)
				Inverter.setChargeState(0)
				print "We have set it to stop"


# Write Realtime Data!!

writer=({"load" : load,
		 "load1" : load1,
		 "load2" : load2,
		 "power":diff,
		 "meter":meter,
		 "soc": soc,
		"time":1000*(time()-timeZone),
		"Niv0" : Niv0/1000.0,
		"Niv1" : Niv1/1000.0,
		"Niv2" : Niv2/1000.0,
		"Niv3" : Niv3/1000.0,
		"Tsell": tpoac
	} ) 

realtime.insert(writer)

















